const CartHttp = require("../../models/CartHttp")
Page({
    data:{
        carts:[],
        allChecked:"",
        sum:0
    },
    async onLoad(){
        var res = await CartHttp.getCart();
        var allChecked=res.data.every(item=>{
            return item.isSelected;
        })
        console.log(allChecked)
        this.setData({
            carts:res.data,
            allChecked
        })
        this.handleSum()
    },
    handleNum(event){
        console.log(event.detail)
        var carts=this.data.carts;
        var {aid}=event.currentTarget.dataset;
        carts.forEach(item=>{
            if(item.id==aid){
                item.productCount=event.detail
            }
        })
        this.setData({
            carts
        })
        this.handleSum()
    },
    handleSelect(event){
        var carts=this.data.carts;
        var {aid}=event.currentTarget.dataset;
        carts.forEach(item=>{
            if(item.id==aid){
                item.isSelected=event.detail
            }
        })
        var allChecked=carts.every(item=>{
            return item.isSelected;
        })
        console.log(allChecked)
        this.setData({
            carts,
            allChecked
        })
        this.handleSum()
    },
    handleAll(event){
        var carts=this.data.carts;
        carts.forEach(item=>{
            item.isSelected=event.detail;
        })
        this.setData({
            allChecked:event.detail,
            carts
        })
        this.handleSum()
    },
    handleSum(){
        var sum=0;
        var carts=this.data.carts;
        carts.forEach(item=>{
            if(item.isSelected){
                sum+=(item.productCount)*(item.productPrice)
            }
        })
        this.setData({
            sum:sum*100
        })
    }
})